<?php

namespace App\Http\Controllers\Manage;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\DB;

use App\Model\Clients;
use Excel;
use Flc\Alidayu\Client;
use App\Model\Manage;
use Flc\Alidayu\App;
use Flc\Alidayu\Requests\AlibabaAliqinFcSmsNumSend;

class ClientController extends Controller
{
    //
    protected static $field = [
        'id' => '编号',
        'create_time' => '创建时间',
        'update_time' => '更新时间',
//        'create_user' => '创建人',
//        'update_user' => '更新人',
        'rank' => '权重',
        'name' => '姓名',
        'gender' => '性别',
        'age' => '年龄',
        'phone' => '电话',
        'email' => '邮箱',
        'project' => '项目名称',
        'time' => '项目时间',
        'address' => '地址',
        'status' => '状态'
    ];

    /**
     * @var int 数据表id
     */
    public $table_id = 13;

    /**
     * CaseController constructor.
     */
    public function __construct()
    {
        parent::__construct($this->table_id);
    }

    public function index() {
        #判断权限
        if($this->rule['view'] == 0){
            return redirect()->back()->withInput()->withErrors('权限不足！');
        }

        $obj = new Clients;
        $check_time = Input::get('check_time');
        $category = Input::get('category');
        $keyword = Input::get('keyword');
        $time = Input::get('create_time');
        $type = Input::get('type');
        $code = Input::get('code');

        if(Input::has('category') && Input::has('keyword')) {
            if(Input::get('category') === 'create_user' || Input::get('category') === 'update_user') {
                $user = Manage::select('id')->where('username','like',"%$keyword%")->get();
                $obj = $obj->whereIn(Input::get('category'),$user);
            }
            else {
                $obj = $obj->where(Input::get('category'),'like',"%$keyword%");
            }
        }
        if(Input::has('check_time')) {
            $start_time = date("Y-m-d 00:00:00",strtotime(substr($time , 0 , 10)));
            $end_time = date("Y-m-d 23:59:59",strtotime(substr($time,-10)));
            $obj = $obj->whereBetween('create_time',[$start_time,$end_time]);
        }

        if(Input::has('type') && Input::has('code')) {
            if($code == 0) {
                $obj = $obj->orderBy($type,'asc');
            }
            if($code == 1) {
                $obj = $obj->orderBy($type,'desc');
            }
        }

        $data = $obj->paginate(10);
        foreach ($data as $k => $value) {
            $timediff = time()-$value['time'];
            $days = intval($timediff/86400);
            if($days < 5) {
                $data[$k]['date'] = date("Y-m-d",$value['time']);
            }
            else {
                $data[$k]['date'] = null;
            }
        }
//        $now = time();
//        $now = strtotime("2017-07-08 13:13:13");
        $field = self::$field;
        return view('manage.client.index',compact('data','field','check_time','category','keyword','time','type','code'));
    }

    /**
     * 载入添加页
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function create() {
        #判断权限
        if($this->rule['add'] == 0){
            return redirect()->back()->withInput()->withErrors('权限不足！');
        }
        return view('manage.client.create');
    }

    /**
     * 添加数据
     * @param Request $request
     * @return Redirect
     */
    public function store(Request $request){
        #判断权限
        if($this->rule['add'] == 0){
            return redirect()->back()->withInput()->withErrors('权限不足！');
        }
        $input = $request->only('rank','name', 'gender','age','phone','email','address','user_id');
        if(empty($input['name']) || empty($input['gender']) || empty($input['age']) || empty($input['phone']) || empty($input['email']) || empty($input['address'])) {
            return redirect()->back()->withInput()->withErrors('缺少参数!');
        }
        $some = Client::where('name',$input['name'])->where('phone',$input['phone'])->first();
        if($some) {
            return redirect()->back()->withInput()->withErrors('该客户已存在!');
        }

        $map = Clients::insert([
            'rank' => $input['rank'],
            'create_user' => $input['user_id'],
            'name' => $input['name'],
            'gender' => $input['gender'],
            'age' => $input['age'],
            'phone' => $input['phone'],
            'email' => $input['email'],
            'address' => $input['address'],
            'status' => 1
        ]);
        if($map) {
            return Redirect::to('/manage/client');
        }
        else {
            return redirect()->back()->withInput()->withErrors('添加失败!');
        }
    }

    public function show($id)
    {
        //
    }

    /**
     * 获取更新数据
     * @param $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function edit($id) {
        #判断权限
        if($this->rule['update'] == 0){
            return redirect()->back()->withInput()->withErrors('权限不足！');
        }
        $data = Clients::where('id',$id)->first();
        return view('manage.client.edit',compact('data'));
    }

    /**
     * 更新数据
     * @param Request $request
     * @param $id
     * @return mixed
     */
    public function update(Request $request,$id) {
        #判断权限
        if($this->rule['update'] == 0){
            return redirect()->back()->withInput()->withErrors('权限不足！');
        }
        $input = $request->only('rank','name', 'gender','age','phone','email','address','user_id');
        if(empty($input['name']) || empty($input['gender']) || empty($input['age']) || empty($input['phone']) || empty($input['email']) || empty($input['address'])) {
            return redirect()->back()->withInput()->withErrors('缺少参数!');
        }
        $some = Clients::where('id','!=',$id)->where('name',$input['name'])->where('phone',$input['phone'])->first();
        if($some) {
            return redirect()->back()->withInput()->withErrors('该客户已存在!');
        }
        $map = Clients::where('id',$id)->update([
            'rank' => $input['rank'],
            'update_user' => $input['user_id'],
            'name' => $input['name'],
            'gender' => $input['gender'],
            'age' => $input['age'],
            'phone' => $input['phone'],
            'email' => $input['email'],
            'address' => $input['address'],
        ]);
        if($map) {
            return Redirect::to('manage/client');
        }
        else {
            return redirect()->back()->withInput()->withErrors('更新失败!');
        }
    }

    /**
     * 删除
     * @param $id
     * @return array
     */
    public function destroy()
    {
        #判断权限
        if($this->rule['delete'] == 0){
            return [
                'code' => 101,
                'msg' => '权限不足！'
            ];
        }
        $id = Input::Get('id');
        $res = Clients::where('id',$id)->delete();
        if($res){
            return [
                'code' => 100,
                'msg' => '删除成功！'
            ];
        }else{
            return [
                'code' => 101,
                'msg' => '删除失败！'
            ];
        }
    }

    /**
     * 状态管理
     * @return array
     */
    public function status()
    {
        #判断权限
        if($this->rule['update'] == 0){
            return [
                'code' => 101,
                'msg' => '权限不足！'
            ];
        }
        $id = Input::get('id');
        $status = Input::get('status');

        if($status == 1) {
            $del = Clients::where('id',$id)->update(['status'=>1,'update_user'=>session('user.id')]);
            $msg = '启用成功！';
        }else{
            $del = Clients::where('id',$id)->update(['status'=>0,'update_user'=>session('user.id')]);
            $msg = '禁用成功！';
        }
        if(!$del){
            return [
                'code'=>101,
                'msg'=>'设置失败！'
            ];
        }
        return [
            'code'=>100,
            'msg'=>$msg
        ];
    }

    public function import() {
        return view('manage.client.import');
    }

    public function input() {
        $s = array();
        $k = array();
        $input_error = null;
        $file = Input::file('file');
        $radio = Input::get('radio');
        if(empty($file)) {
            return redirect()->back()->withInput()->withErrors('请选择上传文件!');
        }

        if($file->isValid()) {
            $allowed_extensions = ["xls","xlsx"];

            if($file->getClientOriginalExtension() && !in_array($file->getClientOriginalExtension(),$allowed_extensions)) {
                return redirect()->back()->withInput()->withErrors('文件格式错误!');
            }
            $destinationPath = 'uploads';  //public文件夹下新建storage/uploads文件夹
            $extension = $file->getClientOriginalExtension();
            $fileName = str_random(10) . '.' . $extension;
            $file->move($destinationPath,$fileName);
            $filePath = asset($destinationPath.'/'.$fileName);
        }
        DB::beginTransaction();

        try {
            $fileExcel = "uploads/".iconv('UTF-8', 'GBK', $fileName);
            //excel文件导入闭包开始
            $result = Excel::load($fileExcel, function($reader) use($radio) {
                $data = $reader->all()->toArray();
//                dump($data);
                foreach ($data as $da => $value) {
                    if($radio ==1 ) {  //跳过重复
                        $map = Clients::where('phone',$value['phone'])->first();
                        if(empty($map)) {
                            $list = Clients::insert([
                                'name'=>$value['name'],
                                'gender'=>$value['gender'],
                                'age'=>$value['age'],
                                'phone'=>$value['phone'],
                                'email'=>$value['email'],
                                'create_user'=>session('user.id'),
                                'address' => $value['address'],
                                'status'=>1,
                            ]);
                        }
                    }
                    if($radio == 2) {  //覆盖重复
                        $map = Clients::where('phone',$value['phone'])->first();
                        if(empty($map)) {
                            $list = Clients::insert([
                                'name'=>$value['name'],
                                'gender'=>$value['gender'],
                                'age'=>$value['age'],
                                'phone'=>$value['phone'],
                                'email'=>$value['email'],
                                'create_user'=>session('user.id'),
                                'address' => $value['address'],
                                'status'=>1,
                            ]);
                        }
                        else {
                            $list = Clients::where('id',$map['id'])->update([
                                'name'=>$value['name'],
                                'gender'=>$value['gender'],
                                'age'=>$value['age'],
                                'phone'=>$value['phone'],
                                'email'=>$value['email'],
                                'update_user'=>session('user.id'),
                                'address' => $value['address'],
                            ]);
                        }
                    }
                }
            });
            DB::commit();
            }
        catch (\Exception $e) {
        return back()->withErrors('导入文件有误!');
            DB::rollBack();
        }
        return Redirect::to('/manage/client');
    }

    public function task() {
        $user_id = Input::get('operation');
        $task = Input::get('task');
        if(empty($user_id)) {
            return redirect()->back()->withInput()->withErrors('请选择成员!');
        }
        $map = Clients::whereIn('id',$user_id)->update(['update_user'=>session('user.id'),'project'=>$task,'time'=>time()]);
        $res = null;
        if($map) {
            foreach ($user_id as $value) {
                $user = Clients::where('id',$value)->first();
                $p = $this->phone($user->name,$task,$user->phone);
                if(!isset($p->code)) {
                    $res .= $user->name.'分配成功,';
                }
                else {
                    $res .= $user->name.'通知失败,';
                }
//                dump($p);
            }
//            exit();
            return Redirect::to('/manage/client')->withInput()->withSuccess($res);
        }
        else {
            return redirect()->back()->withInput()->withErrors('分配失败!');
        }

    }

    public function phone($name,$task,$phone) {
        $config = [
            'app_key'    => '24542002',
            'app_secret' => 'ffa9cca4a675ed9bdd6bf0fd49f5a84b',
        ];

        $client = new Client(new App($config));
        $req    = new AlibabaAliqinFcSmsNumSend;
        $code = rand(100000, 999999);
        $req->setRecNum($phone)
            ->setSmsParam([
                'name' => $name,
                'project' => $task
            ])
            ->setSmsFreeSignName('任务提示')
            ->setSmsTemplateCode('SMS_77230101');

        $resp = $client->execute($req);

        return $resp;
    }
}
